import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Row, Col, Breadcrumb, Table, Timeline, Spin, Button,Modal } from 'antd';
import Title from '../../common/Title';
import WHLabel from '../../common/WH-Label';
import Prompt from '../../common/Prompt'
import moment from 'moment';
import Viewer from '../../toolcase/Viewer';
import api from '../../../api/api';
import { connect } from '../../../states/insurance/insuranceOrderInfo';
import CustomerCart from '../../customerCenter/CustomerCard';
import { connectRouter } from '../../../mixins/router';
import { centToYuan, isValidMoneyCent, refundRountCentPercentToCent } from '../../../helpers/money';
import './index.css'

const styles = {
    text: {
        wordWrap: 'break-word'
    },
    title: {
        display: 'inline-block',
        height: 22,
        lineHeight: '22px',
        backgroundColor: 'white',
        paddingRight: 10,
        marginBottom: '-1px'
    },
    box: {
        borderBottom: 'solid 1px #e0e0e2',
        minHeight: '22px',
        display: 'flex'
    }
}

const PatientOrderStatusChoices = [
    {
        value: '0',
        label: '待激活',
    }, {
        value: '1',
        label: '已承保',
    }, {
        value: '3',
        label: '已完成',
    }, {
        value: '4',
        label: '待退保',
    }, {
        value: '5',
        label: '已退保',
    },{
        value: '8',
        label: '投保失败',
    },{
        value: '9',
        label: '已撤单',
    },{
        value: '10',
        label: '已出险',
    },
];

const payStatus = [
    {
        value: '0', label: '待支付'
    },
    {
        value: '1', label: '支付成功'
    },
    {
        value: '2', label: '支付失败'
    },
]

function getLabel(itemMap, itemValue) {
    const item = itemMap.find(i => i.value == itemValue);
    return item ? item.label : '';
}

function getBirthdayFromIdCard(idCard) {
    var birthday = "";
    if (idCard != null && idCard != "") {
        if (idCard.length == 15) {
            birthday = "19" + idCard.substr(6, 6);
        } else if (idCard.length == 18) {
            birthday = idCard.substr(6, 8);
        }

        birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
    }

    return birthday;
}

class InsuranceOrderInfo extends Component {

    constructor(props) {
        super(props);
        this.insuranceId = this.props.match.params.insuranceId;
        this.props.getInsuranceOrderInfos(this.insuranceId);
        this.state = {
            loading: false,
            orderList: [],
            queResultModal:false
        }
    }

    async componentDidMount() {
    }

    componentWillReceiveProps(props) {
        if (this.insuranceId !== props.match.params.insuranceId) {
            this.insuranceId = this.props.match.params.insuranceId;
            this.props.resetPage();
        }
    }
    get backToIndex() {
        // 由原来跳转会员服务订单，改为跳转保险订单列表
        if (this.props.router.query.r && this.props.router.query.r.indexOf('/InsuranceOrderList2') === 0) {
            return this.props.router.query.r;
        } else {
            return '/InsuranceOrderList2';
        }
    }

    formatMoney(num, digits) {
        num = Number(num);
        if (isValidMoneyCent(num)) {
            return `¥${centToYuan(num, digits || 2)}`;
        } else {
            return '-';
        }
    }

    openImg(pictures) {
        const pic = pictures.map((p) => { return { url: p, alt: p } });
        Viewer(pic, {
            navbar: false,
            toolbar: true,
            title: false,
        });
    }
    // 显示会员卡片
    showCustomerCard = (id) => {
        // console.log('showCustomerCard id:', id);
        this.setState({
            customerCardVisible: true,
            currentCustomerId: id,
        });
    };
    hideCustomerCard = () => {
        this.setState({
            customerCardVisible: false,
        });
    };
    // 查看问询的结果
    checkQueResult=()=>{
        this.setState({
            queResultModal:true
        })
    }
    hideQueResultModal=()=>{
        this.setState({
            queResultModal:false
        })
    }

    // 渲染众惠的问询
    renderZhQuesResult(healthInquiries){
        // 对结果进行分组 base一组，expand一组（）
        let baseResults = []
        let expandResults = []
        healthInquiries.results.forEach((item,index)=>{
            // if(item.code && item.code.indexOf('base') > -1){
            if(index < 4){
                baseResults.push(item)
            }else {
                expandResults.push(item)
            }
        })
        return (
            <div className="q-wrap">
                <div className="tip" style={{marginBottom:'10px'}}>
                    <span style={{padding:'2px 8px',borderRadius:'5px',background:'crimson',color:'white',marginRight:'5px',fontSize:'12px'}}>重要</span>
                    <span style={{color:'crimson'}}>为了保证被保人的保险权益在理赔时不受影响，请确认被保险人的健康状况是否符合投保条件。</span>
                </div>
                {
                    baseResults.map((item,index)=>{
                        return (
                            <div className="base" key={index}>
                                <div className="ques" style={{marginBottom:'10px'}}>
                                    <span>{item.code && item.code.replace(/base|expand/,'') || 'Q' + (index + 1)}、</span>
                                    <span>{item.question.replace(/（\d+）/,'')}</span>
                                </div>
                            </div>
                        )
                    })
                }
                <div className="ans" style={{ padding:'10px',marginBottom:'20px'}}>
                    <Button type="primary" ghost>以上全否</Button>
                </div>
                <div className="expand">
                    <div className="tip" style={{marginBottom:'10px'}}>
                        <span style={{padding:'2px 8px',borderRadius:'5px',background:'crimson',color:'white',marginRight:'5px',fontSize:'12px'}}>重要</span>
                        <span style={{color:'crimson'}}>被保险人正在或者曾经患有下列疾病</span>
                    </div>
                </div>
                {
                    expandResults.map((item,index)=>{
                        return (
                            <div className="base" key={index}>
                                <div className="ques" style={{marginBottom:'10px'}}>
                                    <span>{item.code && item.code.replace(/base|expand/,'') || 'Q' + (index + 1)}、</span>
                                    <span>{item.question.replace(/（\d+）/,'')}</span>
                                </div>
                                <div className="ans" style={{ padding:'10px',marginBottom:'20px'}}>
                                    <Button type="primary" ghost>{item.answer==='1' ? '是' : item.answer === '0' ? '否' : item.answer}</Button>
                                </div>
                            </div>
                        )
                    })
                }
                {
                    healthInquiries.waiver ? (
                        <div className="waiver" style={{marginTop:'10px'}}>
                            <div className="tip" style={{marginBottom:'10px'}}>
                                因下列情形之一导致被保险人支出医疗费用的或发生如下列明的医疗费用，本社不承担保险金给付责任：
                            </div>
                            <div>{healthInquiries.waiver}</div>
                        </div>
                    ) : ''

                }


            </div>
        )
    }

    renderAnQuesResult = (healthInquiries)=>{
        let q1AnsArr = ['恶性肿瘤(含原位癌、白血病、肉瘤)']
        let q2AnsArr = []
        let q3AnsArr = []
        let q4AnsArr = []
        // healthInquiries.results.forEach(item=>{

        // })
        // return
        return ''
    }
    // 渲染健康问询
    renderQueResult=(insuranceInfo)=>{
        console.log('healthInquiries,',healthInquiries)
        let healthInquiries = insuranceInfo.healthInquiries
        if(healthInquiries && healthInquiries.results){
            if(insuranceInfo.company === '众惠'){
                return this.renderZhQuesResult(healthInquiries)
            }else{
                return this.renderAnQuesResult(healthInquiries)
            }
            // return (
            //     healthInquiries.results.map((item,index)=>{
            //         return (
            //             <div key={index} className="q-wrap">
            //                 <div className="ques">
            //                     <span>{item.code.replace(/base|expand/,'')}、</span>
            //                     <span>{item.question.replace(/（\d+）/,'')}</span>
            //                 </div>
            //                 <div className="ans" style={{ padding:'10px',marginBottom:'20px'}}>
            //                     <Button type="primary" ghost>{item.answer==='1' ? '是' : item.answer === '0' ? '否' : item.answer}</Button>
            //                 </div>
            //             </div>
            //         )
            //     })
            // )
        }else{
            return '该保险无问询结果！'
        }
    }
    render() {
        const { loading, orderList } = this.state;
        const data = this.props.insuranceOrderInfo.payload || {};
        const insuranceInfo = data || {};
        const columns = [
            {
                title: '子编码',
                dataIndex: 'seq',
                key: 'seq',
            }, {
                title: '保障条款',
                dataIndex: 'clause',
                key: 'clause',
            }, {
                title: '保额',
                dataIndex: 'coverageAmount',
                key: 'coverageAmount',
            }, {
                title: '免赔额',
                dataIndex: 'deductibleAmount',
                key: 'deductibleAmount',
            }, {
                title: '报销比例',
                dataIndex: 'scale',
                key: 'scale',
            }
        ];
        const tableFoot = <div>
            <div style={{ float: 'left' }}>
                <div>
                    {insuranceInfo.pdfUrl ? <span>保险凭证：<a style={{ color: '#108ee9' }} download='d_file' href={insuranceInfo.pdfUrl.replace('http','https') || ''}>保险凭证.pdf</a></span> : null}
                </div>
            </div>
        </div>
        return <Spin
            spinning={this.props.insuranceOrderInfo.status === 'pending'}
        >
            <div className='insurance_order_info'>
                <CustomerCart
                    id={this.state.currentCustomerId}
                    visible={this.state.customerCardVisible}
                    hideCustomerCard={this.hideCustomerCard}
                ></CustomerCart>
                <Breadcrumb className='breadcrumb-box'>
                    <Breadcrumb.Item>
                        <Link to={this.backToIndex}>保险订单列表</Link>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        保险订单详情
                </Breadcrumb.Item>
                </Breadcrumb>
                <Title text='保险订单号' num={insuranceInfo.sequenceNo} left={5}>
                    <Prompt text={getLabel(PatientOrderStatusChoices, insuranceInfo.status) || '投保中'} />
                </Title>
                <div style={{ backgroundColor: '#fff' }}>
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={8}>
                            <WHLabel title='服务订单号：' text={insuranceInfo.orderNo} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='保单号：' text={insuranceInfo.status == 0 ? '' : insuranceInfo.insuranceOrdrNo} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='保险期间：' text={insuranceInfo.status == 0 ? '' : insuranceInfo.startDate ? `${insuranceInfo.startDate || '-'}至${insuranceInfo.endDate || '-'}` : ''} />
                        </Col>
                    </Row>
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={8}>
                            <WHLabel title='服务产品名称：' text={insuranceInfo.productName || '-'} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='保险类型：' text={insuranceInfo.insuranceType == 1 ? '个险' : insuranceInfo.insuranceType == 2 ? '团险' : '-'} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='产品编码：' text={insuranceInfo.productCode || '-'} />
                        </Col>
                    </Row>
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={8}>
                            <WHLabel title='等待期：' text={insuranceInfo.delayDays || insuranceInfo.delayDays == 0 ? insuranceInfo.delayDays + '天' : '-'} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='承保公司：' text={insuranceInfo.company || '-'} />
                        </Col>
                        {
                            // 只有团险才加团险投保单流水号字段
                            insuranceInfo.insuranceType == 2 ? (
                                <Col className='label-col' span={8}>
                                    <WHLabel title='团险投保单流水号：' text={insuranceInfo.groupOrderNo || '-'} />
                                </Col>
                            ) :''
                        }
                    </Row>
                    <Row className='label-box' gutter={40}>
                        {
                            // 只有团险才加团险投保单流水号字段
                            insuranceInfo.insuranceType == 2 ? (
                                <Col className='label-col' span={8}>
                                    <WHLabel title='交易订单号：' text={insuranceInfo.zhonghuiSequenceNo || '-'} />
                                </Col>
                            ) :''
                        }
                    </Row>



                    <Title text='保险条款' left={5} />
                    <div className="table-box tableBox" >
                        <Table loading={loading} dataSource={insuranceInfo.clauses} rowKey={record => record.seq} columns={columns} pagination={false} bordered={false} footer={() => { return tableFoot }} />
                    </div>
                    {/* 查看健康问询结果 */}
                    {/*
                    <Title text='问询结果' left={5} />
                    <div className="que-result" style={{padding:'20px'}}>
                        问询结果：<span style={{color:'blue',textDecoration:'underline',cursor:'pointer'}} onClick={this.checkQueResult}>查看</span>
                        <Modal
                        title="问询结果"
                        visible={this.state.queResultModal}
                        onOk={this.hideQueResultModal}
                        onCancel={this.hideQueResultModal}
                        width="1000px"
                        >
                            {this.renderQueResult(insuranceInfo)}
                        </Modal>
                    </div>
                    */}
                    <Title text='订单流水' left={5} />
                    <Timeline className='timeline-box'>
                        {
                            insuranceInfo && insuranceInfo.logs && insuranceInfo.logs.length ? insuranceInfo.logs.map((item, index) => {
                                return (
                                    <Timeline.Item key={index}>
                                        <span>{moment(item.date).format('YYYY-MM-DD HH:mm:ss')}</span>
                                        {item.content}
                                    </Timeline.Item>
                                )
                            }) : null
                        }
                    </Timeline>
                    <Title text='被保人信息' left={5} />
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={6}>
                            <div style={{ 'cursor': 'pointer' }} onClick={() => { this.showCustomerCard(insuranceInfo.insuredId) }}>
                                <WHLabel title='被保人' text={insuranceInfo && insuranceInfo.insuredName} />
                            </div>
                        </Col>
                        {/* <Col className='label-col' span={6}>
                            <WHLabel title='身份证号' text={insuranceInfo && insuranceInfo.insuredIdCard} />
                        </Col> */}
                        <Col className='label-col' span={6}>
                            <WHLabel title='性别/年龄' text={`${insuranceInfo && insuranceInfo.sex == 1 ? '男' : insuranceInfo.sex == 0 ? '女' : '-'} / ${insuranceInfo && insuranceInfo.age || '-'}`} />
                        </Col>
                        <Col className='label-col' span={6}>
                            <WHLabel title='生日' text={getBirthdayFromIdCard(insuranceInfo && insuranceInfo.insuredIdCard)} />
                        </Col>
                        <Col className='label-col' span={6}>
                            <WHLabel title='医保类型' text={'城镇职工'} />
                        </Col>
                    </Row>
                    <Row className='label-box' gutter={40}>

                        <Col className='label-col' span={6}>
                            <WHLabel title='在职状态' text={'在职'} />
                        </Col>
                        <Col className='label-col' span={6}>
                            <WHLabel title='职业类别' text={'一类'} />
                        </Col>
                        <Col className='label-col' span={6}>
                            <WHLabel title='职业代码' text={insuranceInfo && insuranceInfo.professionCode} />
                        </Col>
                    </Row>
                    <Title text='受益人信息' left={5} />
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={8}>
                            <WHLabel title='受益人' text={insuranceInfo && insuranceInfo.beneficiary} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='开户行' text={insuranceInfo && insuranceInfo.brankName} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='银行账号' text={insuranceInfo && insuranceInfo.brankCardNo} />
                        </Col>
                    </Row>
                    <Title text='系统信息' left={5} />
                    <Row className='label-box' gutter={40}>
                        <Col className='label-col' span={8}>
                            <WHLabel title='创建人' text={insuranceInfo && insuranceInfo.createBy} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='创建时间' text={insuranceInfo && insuranceInfo.createDate} />
                        </Col>
                        <Col className='label-col' span={8}>
                            <WHLabel title='创建来源' text={insuranceInfo && insuranceInfo.channel} />
                        </Col>
                        <Col className="label-col" span={24}>
                            <WHLabel title="备注：" text={insuranceInfo.remarks} />
                        </Col>
                    </Row>
                </div>
            </div>
        </Spin>
    }
}

export default connectRouter(connect(InsuranceOrderInfo));
